﻿using System;
using System.Text;

namespace ThresholdAssistant.Tools.Security
{
    /// <summary>
    /// 密码转换工具类
    /// </summary>
    public class PasswordConvertUtil
    {
        /// <summary>
        /// 
        /// </summary>
        private static string[] _codeList = new string[36] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
            "d", "e", "f", "g", "h", "i","l", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };

        /// <summary>
        /// 随机生成密码
        /// </summary>
        /// <returns></returns>
        public static string GenPassword()
        {
            var length = GenPasswordLength(8, 16);
            return GenPasswordCode(length);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="password">明文密码</param>
        /// <returns></returns>
        public static string Encrypt(string password)
        {
            if (string.IsNullOrEmpty(password))
                return password;

            return $"{GenPasswordCode(4)}{Base64Util.ToBase64(GenPasswordCode(4) + password)}";
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string Decrypt(string password)
        {
            try
            {
                if (string.IsNullOrEmpty(password))
                    return password;

                return Base64Util.Base64ToString(password.Substring(4)).Substring(4);
            }
            catch (Exception)
            {
            }
            return password;
        }

        /// <summary>
        /// 随机生成密码长度
        /// </summary>
        /// <param name="minLength">最小长度</param>
        /// <param name="maxLength">最大长度</param>
        /// <returns></returns>
        private static int GenPasswordLength(int minLength, int maxLength)
        {
            Random rand = new Random((unchecked((int)DateTime.Now.Ticks)));
            return rand.Next(minLength, maxLength);
        }

        /// <summary>
        /// 随机生成密码Code
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private static string GenPasswordCode(int length)
        {
            StringBuilder builderStr = new StringBuilder();
            Random rand = new Random((unchecked((int)DateTime.Now.Ticks)));
            for (int i = 0; i < length; i++)
            {
                var index = rand.Next(_codeList.Length);
                var code = _codeList[index];
                builderStr.Append(code);
            }
            return builderStr.ToString();
        }
    }
}